package My.Nhom2.ServiceSearch;

import java.util.ArrayList;
import android.R.string;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


/**
 * The Class DatabaseHelper.
 */
public class DatabaseHelper extends SQLiteOpenHelper {

    /** The Constant DATABASE_NAME. */
    private static final String DATABASE_NAME = "servicesdatabase.sqlite";
    /** Doi tuong dung de goi query. */
    private SQLiteDatabase db;
    /** So cot cua du lieu chinh. */
    private boolean[] isUse;
    /** So luong.*/
    private final int count = 6;
    /** Vi tri de xet cot du lieu.*/
    private final int indexColumn = 2;
    /** Chua du lieu tu cac bang rieng biet.*/
    private ArrayList<ArrayList<Cursor>> specDatas;
    /** Du lieu can duoc nhan. */
    private ArrayList<ArrayList<Cursor>> mulDatas;
    /** Chua du lieu tu bang DULIEU(nhieu bang).*/
    private ArrayList<ArrayList<Cursor>> mainDatas;
    /** Chua du lieu da lay cai chung tu mainDatas. */
    private ArrayList<MainDatabase> finalData;
    /** Mang bool danh dau cot nao co du lieu. */
    private boolean[] haveData;
    /** ArrayList chua cac MenuItem */
    ArrayList<ItemMenu> MenuList = new ArrayList<ItemMenu>();
    /** Bang ma so cua bang du lieu chinh.*/
    /** Ten cac bang.*/
//    private static String[] tableName = {
//    	"TUKHOADIADIEM",
 //   	"TUKHOADICHVU",
//    	"TUKHOAPHUONG",
 //   	"TUKHOADUONG",
  //  	"TUKHOAQUANHUYEN",
 //   	"TUKHOATINHTHANH"
  //  };
  //  /** Ten cac cot can kiem tra.*/
  //  private static String[] columnName = {
   // 	"TuKhoaTenDiaDiem",
  //  	"TuKhoaDichVu",
  //  	"TuKhoaPhuong",
  //  	"TuKhoaDuong",
  //  	"TuKhoaQuanHuyen",
  //  	"TuKhoaTinhThanh"
  //  };
  //  /** Ten cac cot trong bang du lieu chinh.*/
  //  private static String[] mainColumnName = {
   // 	"MaTenDiaDiem",
   // 	"MaDichVu",
   // 	"MaPhuong",
    //	"MaDuong",
    //	"MaQuanHuyen",
    //	"MaTinhThanh"
    //};
    private static String[] tableName = {
    	"TUKHOADICHVU",
    	"TUKHOAQUANHUYEN",
    	"TUKHOADIADIEM",    	
    	"TUKHOAPHUONG",
    	"TUKHOADUONG",    	
    	"TUKHOATINHTHANH"
    };
    /** Ten cac cot can kiem tra.*/
    private static String[] columnName = {
    	"TuKhoaDichVu",
    	"TuKhoaQuanHuyen",
    	"TuKhoaTenDiaDiem",    	
    	"TuKhoaPhuong",
    	"TuKhoaDuong",    	
    	"TuKhoaTinhThanh"
    };
    /** Ten cac cot trong bang du lieu chinh.*/
    private static String[] mainColumnName = {
    	"MaDichVu",
    	"MaQuanHuyen",
    	"MaTenDiaDiem",
    	"MaPhuong",
    	"MaDuong",
    	"MaTinhThanh"
    };
    /**
     * Instantiates a new database helper.
     *
     */
    public DatabaseHelper() {
         super(null, null, null, 1);
    }

    /**
     * Instantiates a new database helper.
     *
     * @param context Context chinh
     */
    public DatabaseHelper(final Context context) {
        super(context, DATABASE_NAME, null, 1);
        db = this.getReadableDatabase();
        isUse = new boolean[count];
        specDatas = new ArrayList<ArrayList<Cursor>>();
        mulDatas = new ArrayList<ArrayList<Cursor>>();
        mainDatas = new ArrayList<ArrayList<Cursor>>();
        finalData = new ArrayList<MainDatabase>();
        haveData = new boolean[count];
        //Init
        for (int i = 0; i < count; ++i) {
        	specDatas.add(new ArrayList<Cursor>());
        	mainDatas.add(new ArrayList<Cursor>());
        	//mulDatas.add(new ArrayList<Cursor>());
        	haveData[i] = false;
        }
    }

     /* (non-Javadoc)
     * @see android.database.sqlite.SQLiteOpenHelper#onCreate
     * (android.database.sqlite.SQLiteDatabase)
     */
    @Override
    public void onCreate(final SQLiteDatabase db1) {

    }

    /* (non-Javadoc)
     * @see android.database.sqlite.SQLiteOpenHelper#
     * onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
    */
    @Override
    public void onUpgrade(final SQLiteDatabase db1,
    		final int oldVersion, final int newVersion) {


    }

    /**
     * Gets the query.
     *
     * @param str Chuoi can tim kiem
     * @return Mang cac phan tu du lieu
     */
    /*public final ArrayList<DataService> getQuery(final String str) {
        if (!db.isOpen()) {
           db = this.getReadableDatabase();
        }

        for (int i = 0; i < count; ++i) {
        	isUse[i] = true;
        }

		Cursor[] tCurs = queryKeys(str);
        Cursor[] curs = queryDataFromDULIEUTable(tCurs);

        ArrayList<DataService> datas = addDataQueriedToArrayList(curs);

		return datas;
	}*/
    /**.
     *
     * Xoa du lieu o specDatas
     *
     */
    public final void clearSearchData() {
    	isUse = new boolean[count];
    	specDatas.clear();
        specDatas = new ArrayList<ArrayList<Cursor>>();
        mainDatas.clear();
        mainDatas = new ArrayList<ArrayList<Cursor>>();
        mulDatas.clear();
        mulDatas = new ArrayList<ArrayList<Cursor>>();
        finalData.clear();
        finalData = new ArrayList<MainDatabase>();
        haveData = new boolean[count];
        //Init
        for (int i = 0; i < count; ++i) {
        	specDatas.add(new ArrayList<Cursor>());
        	mainDatas.add(new ArrayList<Cursor>());
        	//mulDatas.add(new ArrayList<Cursor>());
        	haveData[i] = false;
        }
    }
    /**
     * GetQuery Ver3
     */
    public final ArrayList<DataService> getQueryVer3(final ArrayList<String> input) {
    	//Xoa du lieu cu
    	clearSearchData();
    	//Tim data
    	int count = input.size();
    	int start = 0;
    	int end = count - 1;
    	String str;
    	while(start < count) {
    		str = GetSearchString(input, start, end);
    		str.trim();
    		if(searchAllTableVer2(str)) {
    			start = end + 1;
    			end = count - 1;
    		}
    		else {
    			--end;
    			if(start > end) {
    				break;
    			}
    		}    			
    	}
    	//X Du lieu va tra ve
    	return getDataVer3(XDuLieu2());
    }
    /**.
     * GetQuery Ver2.0
     * @param input chuoi input
     */
    /*public final ArrayList<DataService> getQueryVer2(final ArrayList<String> input) {
    	//Xoa du lieu cu
    	clearSearchData();
    	//Tim specdata
    	int count = input.size();
    	int start = 0;
    	int end = count -1;
    	String str;
    	while(start < count) {
    		str = GetSearchString(input, start, end);
    		str.trim();
    		if(searchAllTable(str)) {
    			start = end + 1;
    			end = count - 1;
    		}
    		else {
    			--end;
    			if(start > end) {
    				break;
    			}
    		}
    	}
    	
    	//Lay data vao mainData
    	getDataFromDuLieu();
    	//Nhan cac cot
    	XDuLieu();
    	//Chuyen sang dinh dang
    	return getData();
    }*/
    
    /**
     * Tao ra chuoi tim kiem
     * @param input Chuoi truyen vao
     * @param start index bat dau
     * @param end index ket thuc
     * 
     */
    private String GetSearchString(final ArrayList<String> input, int start, int end) {
    	int tStart = start;
    	String str = "";

    	while(tStart <= end) {
    		str += input.get(tStart) + ' ';
    		++tStart;
    	}
    	str = str.substring(0, str.length() - 1);
    	
    	str.trim();
    	return str;
    }
    /**.
     * Tim tung tu khoa tuong ung voi moi bang
     *@param input Chuoi tu khoa
     *@return Cho biet co thanh cong hay khong
     */
    public final boolean searchAllTable(final String input) {
    	int i;
    	boolean success = false;
    	for (i = 0; i < count; ++i) {
    		String str = "Select * from " + tableName[i] + " where "
                    + '\'' + input + '\'' + " = " + columnName[i];
    		Cursor tCur = db.rawQuery(str, null);
    		if (tCur.moveToFirst()) {
    			specDatas.get(i).add(tCur);
    			haveData[i] = true;
    			success = true;
    			break;
    		}
    	}

    	return success;
    }
    /**.
     * Tim tung tu khoa tuong ung voi moi bang ver 2
     *@param input Chuoi tu khoa
     *@return Cho biet co thanh cong hay khong
     */
    public final boolean searchAllTableVer2(final String input) {
    	int i;
    	boolean success = false;
    	ArrayList<Cursor> arrCur = new ArrayList<Cursor>();
    	for (i = 0; i < count; ++i) {
    		String str = "Select * from " + tableName[i] + " where "
                    + '\'' + input + '\'' + " = " + columnName[i];
    		Cursor tCur = db.rawQuery(str, null);
    		
    		if(!tCur.moveToFirst()) {
    			continue;
    		}
    		do {
    			Cursor tCur2 = getDataFromDuLieuVer2(tCur, i);
    			if(tCur2 != null) {
    				arrCur.add(tCur2);
    				success = true;
    			}
    		}
    		while(tCur.moveToNext());
    	}
    	if(!arrCur.isEmpty()) {
    		mulDatas.add(arrCur);
    	}
    	return success;
    }
    
    /**.
     * Tu spec data lay ra gia tri tuong ung cua bang du lieu chinh.
     * Luc nay mainDatas se co nhieu cot tuong ung chua ghep lai.
     */
    private Cursor getDataFromDuLieuVer2(Cursor cur, int index) {
    	Cursor tCur;
    	tCur = db.rawQuery(
    		"select * from DULIEU where DULIEU."
    		+ mainColumnName[index] + " = "
               + cur.getInt(indexColumn), null);
    	if(tCur.getCount() == 0)
    		return null;
    	return tCur;
    }
    
    /**.
     * Tu spec data lay ra gia tri tuong ung cua bang du lieu chinh.
     * Luc nay mainDatas se co nhieu cot tuong ung chua ghep lai.
     */
    private void getDataFromDuLieu() {
    	int i, j;
    	for (i = 0; i < count; ++i) {
    		if(!haveData[i])
    			continue;
    		for (j = 0; j < specDatas.get(i).size(); ++j) {
    			Cursor tCur;
    			tCur = db.rawQuery(
           		     "select * from DULIEU where DULIEU."
    			     + mainColumnName[i] + " = "
                     + specDatas.get(i).get(j).getInt(indexColumn), null);
    			if (tCur.moveToFirst()) {
    				mainDatas.get(i).add(tCur);
    			}
    		}
    	}

    }
    
    /**
     * Nhan cac cot cua mainDatas voi nhau.
     * Tim ra gia tri chung cua tu khoa.
     */
    private void XDuLieu() {
    
    	int firstDataColumn = -1;
    	int[] haveDataList = new int[count];
    	int lengthDataList = 0;
    	//Tim cot gia tri dau tien
       for (int i = 0; i < count; ++i) {
    	   if(!haveData[i])
    		   continue;
    	   firstDataColumn = i;
    	   break;
       }
       //Tim tat ca cac gia tri
       for (int i = firstDataColumn + 1; i < count; ++i) {
    	   if(haveData[i]) {
    		   haveDataList[lengthDataList] = i;
    		   ++lengthDataList;
    	   }
       }
       //Do cot dau tien voi tat ca cac cot con lai
       if(firstDataColumn == -1)
    	   return;
       int count1 = mainDatas.get(firstDataColumn).size();
       for(int i = 0; i < count1; ++i) {
    	   int count2 = mainDatas.get(firstDataColumn).get(i).getCount();
    	   mainDatas.get(firstDataColumn).get(i).moveToFirst();
    	   for(int m = 0; m < count2; ++m) {
    		   boolean fMatchValue = true;
    		   //Gia tri ma can so sanh
    		   int k = mainDatas.get(firstDataColumn).get(i).getInt(0);
    		   //So sanh voi cac cot con lai
    		   for(int j = 0; j < lengthDataList; ++j) {
    			   if(!haveValue(k, haveDataList[j])) {
    				   fMatchValue = false;
    			   }
    		   }
    		   //Neu thoa man thi them vao final
    		   if(fMatchValue) {
    			   MainDatabase tMain = new MainDatabase();
    			   tMain.setMaDuLieu(mainDatas.get(firstDataColumn).get(i).getInt(0));
    			   tMain.setMaDichVu(mainDatas.get(firstDataColumn).get(i).getInt(1));
    			   tMain.setMaTenDiaDiem(mainDatas.get(firstDataColumn).get(i).getInt(2));
    			   tMain.setSoNha(mainDatas.get(firstDataColumn).get(i).getString(3));
    			   tMain.setMaDuong(mainDatas.get(firstDataColumn).get(i).getInt(4));
    			   tMain.setMaPhuong(mainDatas.get(firstDataColumn).get(i).getInt(5));
    			   tMain.setMaQuanHuyen(mainDatas.get(firstDataColumn).get(i).getInt(6));
    			   tMain.setMaTinhThanh(mainDatas.get(firstDataColumn).get(i).getInt(7));
    			   tMain.setKinhDo(mainDatas.get(firstDataColumn).get(i).getString(8));
    			   tMain.setViDo(mainDatas.get(firstDataColumn).get(i).getString(9));
    			   tMain.setChuThich(mainDatas.get(firstDataColumn).get(i).getString(10));
    			   
    			   finalData.add(tMain);
    		   }
    		   
    		   mainDatas.get(firstDataColumn).get(i).moveToNext();
    	   }
       }       
    }
    
    /**
     * Nhan cac cot cua mainDatas voi nhau.
     * Tim ra gia tri chung cua tu khoa.
     * Version 2
     */
    private ArrayList<ArrayList<MainDatabase>> XDuLieu2() {
    	
    	ArrayList<ArrayList<MainDatabase>> result =
    			 new  ArrayList<ArrayList<MainDatabase>>();
    	if(mulDatas.size() == 0)
    		return result;
    	int length = mulDatas.size();
    	int[] mark = new int[length];
    	ArrayList<ArrayList<Integer>> markTempData = new ArrayList<ArrayList<Integer>>();
    	for(int i = 0; i < length; ++i) {
    		mark[i] = 0;
    		markTempData.add(new ArrayList<Integer>());
    	}
    	ArrayList<Integer> tArray;
    	ArrayList<MainDatabase> tMain;
    	int j;
    	boolean end = false;
    	if(length == 1) {
			int length3 = mulDatas.get(0).size();
			for(int k = 0; k < length3; ++k) {
				tMain = cursorToArrMainDatabase(mulDatas.get(0).get(k));
 				result.add(tMain);
			}
			end = true;
		}
    	
    	while(!end) {
    		
    		tArray = arrayMaDuLieuOfCursor(mulDatas.get(0).get(mark[0]));
    		for(j = 1; j < length - 1; ++j) {
    			if(tArray.size() == 0) {
    				break;
    			}
    			tArray = X2CursorGetIndexData(tArray, mulDatas.get(j).get(mark[j]));
    			
    		}
    		if(tArray.size() > 0) {
    			tMain = X2CursorGetMainData(tArray, mulDatas.get(j).get(mark[j]));
    			if(tMain.size() > 0)
    				result.add(tMain);
    		}
    		//Chinh lai mark
  			int temp = length - 1;
    		++mark[temp];
    		while(mark[temp] >= mulDatas.get(temp).size()) {
    			if(temp <= 0) {
    				end = true;
    				break;
    			}
     			mark[temp] = 0;
    			++mark[temp - 1];
    			--temp;
    		}
    		
    	}
    	
    	return result;

    }
    
    /**.
     * Nhan 2 Cursor voi nhau, tra ve cac phan tu MainDatabase chung giua chung
     * @param cur1 Bang can nhan thu nhat
     * @param cur2 Bang can nhan thu hai
     * @param output Ket qua nhan duoi dang chuoi integer
     * @return Mang ket qua MainDatabase
     *
     */
    private ArrayList<MainDatabase> X2CursorGetMainData(ArrayList<Integer> index1, Cursor cur2) {
    	ArrayList<int[]> a = new ArrayList<int[]>();
    	ArrayList<MainDatabase> MutualItem = new ArrayList<MainDatabase>();
    	int numberOfRowsOfCur1 = index1.size();
    	int numberOfRowsOfCur2 = cur2.getCount();
	   	//int[] arrayMaDuLieuOfCursor1 =
	   	//		arrayMaDuLieuOfCursor(cur1, numberOfRowsOfCur1);
	 	ArrayList<Integer> arrayMaDuLieuOfCursor2 =
	 			arrayMaDuLieuOfCursor(cur2);
	 	//cur1.moveToFirst();
    	cur2.moveToFirst();
    	int pointerCur1 = 0;
    	int lengthCu1 = numberOfRowsOfCur1 - 1;
    	int pointerCur2 = 0;
    	int lengthCu2 = numberOfRowsOfCur2 - 1;
    	int temp1;//vi tri index cua gia tri o vi tri startCur1 trong mang arrayMaDuLieuOfCursor2
    	int temp2;//vi tri index cua gia tri o vi tri startCur2 trong mang arrayMaDuLieuOfCursor1
    	
    	//Chuan bi tim kiem cho 2 con tro cung gia tri
    	temp1 = index1.get(0);
    	temp2 = arrayMaDuLieuOfCursor2.get(0);

    	if(temp1 > temp2) {
    		pointerCur2 = binarySearch(index1.get(pointerCur1),  arrayMaDuLieuOfCursor2, pointerCur2, lengthCu2);
    	}
    	else {
    		pointerCur1 = binarySearch(arrayMaDuLieuOfCursor2.get(pointerCur2),  index1, pointerCur1, lengthCu1);
    	}
    	//Tinh toan
    	while((pointerCur1 <= lengthCu1) && (pointerCur2 <= lengthCu2)) {
    		int aa = index1.get(pointerCur1);
    		int bb = arrayMaDuLieuOfCursor2.get(pointerCur2);
    		if(aa == bb) {
    			MainDatabase tMain = cursorToMainData(cur2, pointerCur2);
    			//output.add(tMain.getMaDuLieu());
    			MutualItem.add(cursorToMainData(cur2, pointerCur2));
    			++pointerCur1;
    			++pointerCur2;
    			continue;
    		}
    		if(index1.get(pointerCur1) 
    				< arrayMaDuLieuOfCursor2.get(pointerCur2)) {
    			++pointerCur1;
    		}
    		else {
    			++pointerCur2;
    		}    		
    	} 		
    		
    	return MutualItem;    	
    }
    /**.
     * Nhan 2 Cursor voi nhau, tra ve cac phan tu MainDatabase chung giua chung
     * @param cur1 Bang can nhan thu nhat
     * @param cur2 Bang can nhan thu hai
     * @param output Ket qua nhan duoi dang chuoi integer
     * @return Mang ket qua MainDatabase
     *
     */
    private ArrayList<Integer> X2CursorGetIndexData(ArrayList<Integer> index1, Cursor cur2) {
    	//ArrayList<int[]> a = new ArrayList<int[]>();
    	ArrayList<Integer> output = new ArrayList<Integer>();
    	//ArrayList<MainDatabase> MutualItem = new ArrayList<MainDatabase>();
    	int numberOfRowsOfCur1 = index1.size();
    	int numberOfRowsOfCur2 = cur2.getCount();
	   	//int[] arrayMaDuLieuOfCursor1 =
	   	//		arrayMaDuLieuOfCursor(cur1, numberOfRowsOfCur1);
	 	ArrayList<Integer> arrayMaDuLieuOfCursor2 =
	 			arrayMaDuLieuOfCursor(cur2);
	 	//cur1.moveToFirst();
    	cur2.moveToFirst();
    	int pointerCur1 = 0;
    	int lengthCu1 = numberOfRowsOfCur1 - 1;
    	int pointerCur2 = 0;
    	int lengthCu2 = numberOfRowsOfCur2 - 1;
    	int temp1;//vi tri index cua gia tri o vi tri startCur1 trong mang arrayMaDuLieuOfCursor2
    	int temp2;//vi tri index cua gia tri o vi tri startCur2 trong mang arrayMaDuLieuOfCursor1
    	
    	//Chuan bi tim kiem cho 2 con tro cung gia tri
    	temp1 = index1.get(0);
    	temp2 = arrayMaDuLieuOfCursor2.get(0);

    	if(temp1 > temp2) {
    		pointerCur2 = binarySearch(index1.get(pointerCur1),  arrayMaDuLieuOfCursor2, pointerCur2, lengthCu2);
    	}
    	else {
    		pointerCur1 = binarySearch(arrayMaDuLieuOfCursor2.get(pointerCur2),  index1, pointerCur1, lengthCu1);
    	}
    	
    	//Tinh toan
    	while((pointerCur1 <= lengthCu1) && (pointerCur2 <= lengthCu2)) {
    		int aa = index1.get(pointerCur1);
    		int bb = arrayMaDuLieuOfCursor2.get(pointerCur2);
    		if(aa == bb) {
    			MainDatabase tMain = cursorToMainData(cur2, pointerCur2);
    			output.add(tMain.getMaDuLieu());
    			//MutualItem.add(cursorToMainData(cur2, pointerCur2));
    			++pointerCur1;
    			++pointerCur2;
    			continue;
    		}
    		if(index1.get(pointerCur1) 
    				< arrayMaDuLieuOfCursor2.get(pointerCur2)) {
    			++pointerCur1;
    		}
    		else {
    			++pointerCur2;
    		}    		
    	} 		
    		
    	return output;    	
    }
    /**.
     * Ham tao mang so nguyen la danh sach cac ma du lieu cua Cursor
     *
     *
     */
    private ArrayList<Integer> arrayMaDuLieuOfCursor(Cursor cur) {
    	ArrayList<Integer> tempArray = new ArrayList<Integer>();
    	int numberOfRows = cur.getCount();
    	if(!cur.moveToFirst())
	   		 return null;
	   	 for(int i = 0; i < numberOfRows; i++){
	   		tempArray.add(cur.getInt(0));
	   		cur.moveToNext();
	   	 }
	   	 return tempArray;
    }
    /**
     * Ham tim kiem nhi phan
     * tra ve index cua gia tri can tim trong mang (neu co)
     * -1 la khong tim thay
     */
    private int binarySearch(int value, ArrayList<Integer> arrayToSearch, int startIndex, int endIndex){
    	
    	int midIndex = -1;
    	while(startIndex <= endIndex){
    		midIndex = (startIndex + endIndex) / 2;
    		if(arrayToSearch.get(midIndex) == value){
    			return midIndex;
    		}
    		if(arrayToSearch.get(midIndex) < value){
    			startIndex = midIndex + 1;
    			continue;
    		}
    		if(arrayToSearch.get(midIndex) > value){
    			endIndex = midIndex - 1;
    			continue;
    		}
    	}
    	return midIndex;
    }
    /**
     * Ham
     */
    private ArrayList<MainDatabase> cursorToArrMainDatabase(Cursor cur) {
    	ArrayList<MainDatabase> result = new ArrayList<MainDatabase>();
    	int length = cur.getCount();
    	for(int i = 0; i < length; ++i) {
    		result.add(cursorToMainData(cur, i));
    	}
    	
    	return result;
    }
    /**
     * 
     * @param cur
     * @param index
     * @return MainDatabase
     */
    private MainDatabase cursorToMainData(Cursor cur, int index) {
    	MainDatabase result = new MainDatabase();
    	
    	//chuyen toi vi tri index
    	cur.moveToPosition(index);
    	
    	//xac lap du lieu cho result
    	result.setMaDuLieu(cur.getInt(0));
    	result.setMaDichVu(cur.getInt(1));
    	result.setMaTenDiaDiem(cur.getInt(2));
    	result.setSoNha(cur.getString(3));
    	result.setMaDuong(cur.getInt(4));
    	result.setMaPhuong(cur.getInt(5));
		result.setMaQuanHuyen(cur.getInt(6));
		result.setMaTinhThanh(cur.getInt(7));
		result.setKinhDo(cur.getString(8));
		result.setViDo(cur.getString(9));
		result.setChuThich(cur.getString(10));
		
    	return result;
    }
    /**
     * Ham phu cho ham XDuLieu.
     * Search mot gia tri nao do trong mot bang mainDatas.
     */
    private boolean haveValue(int value, int dataColumn) {
    	int k;
    	int count1 = mainDatas.get(dataColumn).size();
    	
    	for(int i = 0; i < count1; ++i) {
    		int count2 = mainDatas.get(dataColumn).get(i).getCount();
    		mainDatas.get(dataColumn).get(i).moveToFirst();
    		for(int j = 0; j < count2; ++j) { 
    			k = mainDatas.get(dataColumn).get(i).getInt(0);
    			if(k == value)
    				return true;
    			mainDatas.get(dataColumn).get(i).moveToNext();
    		}
    	}
    	return false;
    }
    /**.
     * Tra ve ket qua DataService
     */
    /*public ArrayList<DataService> getData() {
    	ArrayList<DataService> result = new ArrayList<DataService>();
    	DataService temp = new DataService();
    	
    	for(int i = 0; i < finalData.size(); ++i) {
    		temp = new DataService();
    		temp.maDuLieu = finalData.get(i).getMaDichVu();
    		Cursor tCur1 = null;
    		//Lay ten dich vu
    		tCur1 = db.rawQuery(
        			"select * from DICHVU where MaDichVu = "
        			+ finalData.get(i).getMaDichVu(), null);
    		tCur1.moveToFirst();
        	temp.tenDichVu = tCur1.getString(1);
        	tCur1.close();
        	//Lay ten dia diem///////////////////
        	Cursor tCur2 = null;

        	tCur2 = db.rawQuery(
        			"select * from  TENDIADIEM "
        			+ "where MaTenDiaDiem = "
            			   		+ finalData.get(i).getMaTenDiaDiem(), null);

        	tCur2.moveToFirst();
        	temp.tenDiaDiem = tCur2.getString(1);
        	tCur2.close();
        	//Luu so nha//////
        	temp.soNha = finalData.get(i).getSoNha();

        	//Luu ten duong////
        	Cursor tCur3 = null;
        	tCur3 = db.rawQuery(
        			"select * from  DUONG where MaDuong= "
            	    + finalData.get(i).getMaDuong(), null);
        	
        	tCur3.moveToFirst();
			temp.duong = tCur3.getString(1);
			tCur3.close();
			//Luu ten phuong//////
			Cursor tCur4 = null;

			tCur4 = db.rawQuery(
                "select * from  PHUONG where MaPhuong= "
                + finalData.get(i).getMaPhuong(), null);

			tCur4.moveToFirst();
			temp.phuong = tCur4.getString(1);
			tCur4.close();
			//luu ten quan huyen//////
			Cursor tCur5 = null;
			tCur5 = db.rawQuery(
              "select * from  QUANHUYEN where MaQuanHuyen= "
              + finalData.get(i).getMaQuanHuyen(), null);
			tCur5.moveToFirst();
			temp.quanHuyen = tCur5.getString(1);
			tCur5.close();
			//Luu ten tinh thanh/////
			Cursor tCur6 = null;

            tCur6 = db.rawQuery(
                 "select * from  TINHTHANH where MaTinhThanh= "
                 + finalData.get(i).getMaTinhThanh(), null);
			tCur6.moveToFirst();
			temp.tinhThanh = tCur6.getString(1);
			tCur6.close();

			temp.kinhDo = finalData.get(i).getKinhDo();
			temp.viDo = finalData.get(i).getViDo();
			temp.chuThich = finalData.get(i).getChuThich();
			temp.maDuLieu = finalData.get(i).getMaDuLieu();

			result.add(temp);
    	}
		return result;
    	
    }*/
    /**
     * GetData Ver 3
     */
    public ArrayList<DataService> getDataVer3(ArrayList<ArrayList<MainDatabase>> main) {
    	ArrayList<DataService> result = new ArrayList<DataService>();
    	int length1;
    	length1 = main.size();
    	for(int i = 0; i < length1; ++i) {
    		getDataHelperVer3(main.get(i), result);
    	}
    	
    	return result;
    }
    	
    
    /**
     * Get data ver 3
     */
    public void getDataHelperVer3(ArrayList<MainDatabase> tMain, ArrayList<DataService> result) {

    	DataService temp = new DataService();
    	int tLength = tMain.size();
    	for(int i = 0; i < tLength; ++i) {
    		temp = new DataService();
    		
    		//temp.maDuLieu = tMain.get(i).getMaDuLieu();
    		temp.setMaDuLieu(tMain.get(i).getMaDuLieu());
    		Cursor tCur1 = null;
    		//Lay ten dich vu
    		tCur1 = db.rawQuery(
        			"select * from DICHVU where MaDichVu = "
        			+ tMain.get(i).getMaDichVu(), null);
    		
    		if(tCur1.getCount() == 0) {
    			//temp.tenDichVu = "N/A";
    			temp.setTenDichVu("N/A");
    		}
    		else {
    			tCur1.moveToFirst();
    			//temp.tenDichVu = tCur1.getString(1);
    			temp.setTenDichVu(tCur1.getString(1));
    		}    			
        	
        	tCur1.close();
        	//Lay ten dia diem///////////////////
        	Cursor tCur2 = null;

        	tCur2 = db.rawQuery(
        			"select * from  TENDIADIEM "
        			+ "where MaTenDiaDiem = "
            			   		+ tMain.get(i).getMaTenDiaDiem(), null);
        	if(tCur2.getCount() == 0) {
    			//temp.tenDiaDiem = "N/A";
        		temp.setTenDiaDiem("N/A");
    		}
    		else {
    			tCur2.moveToFirst();
    			//temp.tenDiaDiem = tCur2.getString(1);
    			temp.setTenDiaDiem(tCur2.getString(1));
    		}        	

        	tCur2.close();
        	//Luu so nha//////
        	//temp.soNha = tMain.get(i).getSoNha();
        	temp.setSoNha(tMain.get(i).getSoNha());

        	//Luu ten duong////
        	Cursor tCur3 = null;
        	tCur3 = db.rawQuery(
        			"select * from  DUONG where MaDuong= "
            	    + tMain.get(i).getMaDuong(), null);
        	
        	
        	if(tCur3.getCount() == 0) {
    			//temp.duong = "N/A";
        		temp.setTenDuong("N/A");
    		}
    		else {
    			tCur3.moveToFirst();
    			//temp.duong = tCur3.getString(1);
    			temp.setTenDuong(tCur3.getString(1));
    		}
			tCur3.close();
			//Luu ten phuong//////
			Cursor tCur4 = null;

			tCur4 = db.rawQuery(
                "select * from  PHUONG where MaPhuong= "
                + tMain.get(i).getMaPhuong(), null);
			if(tCur4.getCount() == 0) {
				//temp.phuong = "N/A";
				temp.setTenPhuong("N/A");
			}
			else {
				tCur4.moveToFirst();
				//temp.phuong = tCur4.getString(1);
				temp.setTenPhuong(tCur4.getString(1));
			}
			tCur4.close();
			//luu ten quan huyen//////
			Cursor tCur5 = null;
			tCur5 = db.rawQuery(
              "select * from  QUANHUYEN where MaQuanHuyen= "
              + tMain.get(i).getMaQuanHuyen(), null);
			if(tCur5.getCount() == 0) {
				//temp.quanHuyen = "N/A";
				temp.setTenQuanHuyen("N/A");
			}
			else {
				tCur5.moveToFirst();
				//temp.quanHuyen = tCur5.getString(1);
				temp.setTenQuanHuyen(tCur5.getString(1));
			}
			tCur5.close();
			//Luu ten tinh thanh/////
			Cursor tCur6 = null;

            tCur6 = db.rawQuery(
                 "select * from  TINHTHANH where MaTinhThanh= "
                 + tMain.get(i).getMaTinhThanh(), null);
            if(tCur6.getCount() == 0) {
            	//temp.tinhThanh = "N/A";
            	temp.setTenTinhThanh("N/A");
            }
            else {
            	tCur6.moveToFirst();
            	//temp.tinhThanh = tCur6.getString(1);
            	temp.setTenTinhThanh(tCur6.getString(1));
            }
			tCur6.close();

			//temp.kinhDo = tMain.get(i).getKinhDo();
			temp.setKinhDo(tMain.get(i).getKinhDo());
			//temp.viDo = tMain.get(i).getViDo();
			temp.setViDo(tMain.get(i).getViDo());
			//temp.chuThich = tMain.get(i).getChuThich();
			temp.setChuThich( tMain.get(i).getChuThich());
			//temp.maDuLieu = tMain.get(i).getMaDuLieu();
			

			result.add(temp);
    	}
    	
    }
	/**
	 * Query keys.
	 *
	 * @param str the str
	 * @return the cursor[]
	 */
	public final Cursor[] queryKeys(final String str) {

		Cursor[] tCurs = new Cursor[count];
        //tim cac tu khoa trong bang
        //TUKHOADIADIEM bang voi str, roi tra ket qua ve
		tCurs[0] = db.rawQuery("Select * from TUKHOADIADIEM where "
                          + '\'' + str + '\'' + " = TuKhoaTenDiaDiem", null);

        //tim cac tu khoa trong bang
        //TUKHOADICHVU bang voi str, roi tra ket qua ve
	    tCurs[1] = db.rawQuery("Select * from TUKHOADICHVU where "
                              + '\'' + str + '\'' + " = TuKhoaDichVu", null);

        //tim cac tu khoa trong bang
        //TUKHOAPHUONG bang voi str, roi tra ket qua ve
	    tCurs[2] = db.rawQuery("Select * from TUKHOAPHUONG where "
                              + '\'' + str + '\'' + " = TuKhoaPhuong", null);

         //tim cac tu khoa trong bang
        //TUKHOADUONG bang voi str, roi tra ket qua ve
	    tCurs[count / 2] = db.rawQuery("Select * from TUKHOADUONG where "
                              + '\'' + str + '\'' + " = TuKhoaDuong", null);

        //tim cac tu khoa trong bang
        //TUKHOAQUANHUYEN bang voi str, roi tra ket qua ve
	    tCurs[count - 2] = db.rawQuery(
	    		"Select * from TUKHOAQUANHUYEN where "
                              + '\'' + str + '\'' + " = TuKhoaQuanHuyen", null);

        //tim cac tu khoa trong bang
        //TUKHOATINHTHANH bang voi str, roi tra ket qua ve
	    tCurs[count - 1] = db.rawQuery(
	    		"Select * from TUKHOATINHTHANH where "
                              + '\'' + str + '\'' + " = TuKhoaTinhThanh", null);
	    return tCurs;
	}

	/**
	 * Query data from dulieu table.
	 *
	 * @param tCurs Mang nhap vao
	 * @return Mang tra ve
	 */
	private Cursor[] queryDataFromDULIEUTable(final Cursor[] tCurs) {
		Cursor[] curs = new Cursor[count];

		for (int i = 0; i < count; ++i) {
           if (!tCurs[i].moveToFirst()) {
        		isUse[i] = false;
           }
        }

        if (isUse[0]) {
                curs[0] = db.rawQuery(
        		     "select * from DULIEU where DULIEU.MaTenDiaDiem = "
                     + tCurs[0].getInt(2), null);
                curs[0].moveToFirst();
        }
        if (isUse[1]) {
		        curs[1] = db.rawQuery(
		        "select * from DULIEU where DULIEU.MaDichVu = "
		                + tCurs[1].getInt(2), null);
		        curs[1].moveToFirst();
        }
        if (isUse[2]) {
		        curs[2] = db.rawQuery(
		        "select * from DULIEU where DULIEU.MaPhuong = "
		        + tCurs[2].getInt(2), null);
		        curs[2].moveToFirst();
        }
        if (isUse[count / 2]) {
		        curs[count / 2] = db.rawQuery(
		        	 "select * from DULIEU where DULIEU.MaDuong = "
		              + tCurs[count / 2].getInt(2), null);
		        curs[count / 2].moveToFirst();
        }
        if (isUse[count - 2]) {
		        curs[count - 2] = db.rawQuery(
		       	"select * from DULIEU where DULIEU.MaQuanHuyen = "
		             + tCurs[count - 2].getInt(2), null);
		        curs[count - 2].moveToFirst();
        }
        if (isUse[count - 1]) {
		        curs[count - 1] = db.rawQuery(
		        "select * from DULIEU where DULIEU.MaTinhThanh = "
		                + tCurs[count - 1].getInt(2), null);
		        curs[count - 1].moveToFirst();
        }
		return curs;
	}

	/**
	 * Adds the data queried to array list.
	 *
	 * @param curs Mang nhap vao
	 * @return Mang tra ve
	 */
     /*private ArrayList<DataService> addDataQueriedToArrayList(
                                             final Cursor[] curs) {
		ArrayList<DataService> datas = new ArrayList<DataService>();
		//db.setLockingEnabled(false);
        for (int x = 0; x < count; x++) {
             if (!isUse[x]) {
        		continue;
        	}

	        int nRow = curs[x].getCount();
	        for (int i = 0; i < nRow; ++i) {
	        	DataService tData = new DataService();
	            int temp;
	            Cursor tCur1 = null;
	        	//Lay ten dich vu///////////////////
	            while (db.isDbLockedByOtherThreads()) {

	            }
	            while (db.isDbLockedByCurrentThread()) {

	            }
	        	tCur1 = db.rawQuery(
	        			"select * from DICHVU where MaDichVu = "
	        			+ curs[x].getInt(1), null);
	        	if (tCur1 == null) {
					continue;
	        	}
	        	tCur1.moveToFirst();
	        	tData.tenDichVu = tCur1.getString(1);
	            tCur1.close();
	        	//Lay ten dia diem///////////////////
	        	Cursor tCur2 = null;
	        	temp = curs[x].getInt(2);

	        	while (db.isDbLockedByOtherThreads()) {

	        	}
	        	while (db.isDbLockedByCurrentThread()) {

	        	}
	        	tCur2 = db.rawQuery(
	        			"select * from  TENDIADIEM "
	        			+ "where MaTenDiaDiem = "
	            			   		+ temp, null);

	        	if (tCur2 == null) {
					continue;
	        	}
	        	tCur2.moveToFirst();
	        	tData.tenDiaDiem = tCur2.getString(1);
	        	tCur2.close();
	        	//Luu so nha//////
	        	tData.soNha = curs[x].getString(count / 2);

	        	//Luu ten duong////
	        	Cursor tCur3 = null;

	        	while (db.isDbLockedByOtherThreads()) {

	        	}
	        	while (db.isDbLockedByCurrentThread()) {

	        	}
	        	tCur3 = db.rawQuery(
	        			"select * from  DUONG where MaDuong= "
	            	    + curs[x].getInt(count - 2), null);
	        	if (tCur3 == null) {
					continue;
	        	}
	        	tCur3.moveToFirst();
				tData.duong = tCur3.getString(1);
				tCur3.close();
				//Luu ten phuong//////
				Cursor tCur4 = null;
				while (db.isDbLockedByOtherThreads()) {

				}
				while (db.isDbLockedByCurrentThread()) {

				}

				tCur4 = db.rawQuery(
                    "select * from  PHUONG where MaPhuong= "
                    + curs[x].getInt(count - 1), null);
				if (tCur4 == null) {
					continue;
				}
				tCur4.moveToFirst();
				tData.phuong = tCur4.getString(1);
				tCur4.close();
				//luu ten quan huyen//////
				Cursor tCur5 = null;
				while (db.isDbLockedByOtherThreads()) {

				}
				while (db.isDbLockedByCurrentThread()) {

				}
				tCur5 = db.rawQuery(
                  "select * from  QUANHUYEN where MaQuanHuyen= "
                  + curs[x].getInt(count), null);
				if (tCur5 == null) {
					continue;
				}
				tCur5.moveToFirst();
				tData.quanHuyen = tCur5.getString(1);
				tCur5.close();
				//Luu ten tinh thanh/////
				Cursor tCur6 = null;

				while (db.isDbLockedByOtherThreads()) {

				}
				while (db.isDbLockedByCurrentThread()) {

				}

                tCur6 = db.rawQuery(
                     "select * from  TINHTHANH where MaTinhThanh= "
                     + curs[x].getInt(count + 1), null);
				if (tCur6 == null) {
					continue;
				}
				tCur6.moveToFirst();
				tData.tinhThanh = tCur6.getString(1);
				tCur6.close();

				tData.kinhDo = curs[x].getString(count + 2);
				tData.viDo = curs[x].getString(count + 2 + 1);
				tData.chuThich = curs[x].getString(
						count + 2 + 2);
				tData.maDuLieu = curs[x].getInt(0);

				addDataServiceItemToArrayList(datas, tData);

				curs[x].moveToNext();

	        }
		}
		return datas;
	}*/

	/**
	 * Adds the data service item to array list.
	 *
	 * @param datas Du lieu xuat ra
	 * @param tData Du lieu dau vao
	 */
    /*public final void addDataServiceItemToArrayList(
    		final ArrayList<DataService> datas, final DataService tData) {
        //Kiem tra phan tu tData da co trong
    	//ArrayList chua bang cach so sanh ma du lieu
		boolean notFound = true;
		int temp2 = datas.size();

        for (int j = 0; j < temp2; j++) {
			if (tData.maDuLieu == datas.get(j).maDuLieu) {
				notFound = false;
		 	    break;
		 	}
        }
		if (notFound) {
			datas.add(tData);
		}
	}*/
    /**
	 * Tra ve danh sach menu cua quan an do
	 *
	 * @param MaDuLieu cua quan an can lay menu 
	 * @return rong neu khong co danh sach menu
	 * 
	 */
    public ArrayList<ItemMenu> getMenuList(int MaDuLieu){
    	Cursor cur;
    	MenuList.clear();
    	String query = "select CHITIETDICHVU.MaChiTiet, CHITIETDICHVU.Ten, " +
                "CHITIETDICHVU.GiaTien, CHITIETDICHVU.ChuThich " +
                "from CHITIETDICHVU, CHITIET_DULIEU " +
                "where CHITIET_DULIEU.MaDuLieu = " + Integer.toString(MaDuLieu) + 
                " and CHITIET_DULIEU.MaChiTiet = CHITIETDICHVU.MaChiTiet";
    	
    	cur = db.rawQuery(query, null);
    	if(!cur.moveToFirst())
    		return MenuList;
    	do
    	{
    		ItemMenu item = new ItemMenu(cur.getInt(0), cur.getString(1), cur.getInt(2), cur.getString(3));
    		MenuList.add(item);
    	}
    	while(cur.moveToNext());
    	cur.close();
    	return MenuList;
    }

}